package com.rog.kmzero.server;

import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.rog.kmzero.client.service.GreetingService;
import com.rog.kmzero.domain.KmUser;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) {
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		
		String message = "";
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		if (input.equals("rossano") || input.equals("pippo")){
			KmUser kmUser = new KmUser(input, "Smith");
	        try {
	            pm.makePersistent(kmUser);
	        } finally {
	            pm.close();
	        }
	        
	        message = "stored: " + input;
		}
		else{
			String query = "select from " + KmUser.class.getName() + " where lastName == 'Smith'";
	        List<KmUser> kmUsers = (List<KmUser>) pm.newQuery(query).execute();		
	        
	        message = "retreived: ";
	        
	        if (kmUsers != null){
		        for(KmUser u : kmUsers){
		        	message += " " + u.getFirstName();
		        }
	        }	        
		}

		return "Hello, I " + message;
	}
}
